package com.rfsp.mcp.service;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rfsp.common.base.BaseService;
import com.rfsp.common.log.TrcMsg;
import com.rfsp.common.pojo.po.OrgPO;
import com.rfsp.common.pojo.po.UserPO;
import com.rfsp.common.pojo.sdto.PageSDTO;
import com.rfsp.common.service.AreaService;
import com.rfsp.common.service.OrgService;
import com.rfsp.common.service.UserService;
import com.rfsp.common.shiro.ShiroUtils;
import com.rfsp.common.util.JsonUtil;
import com.rfsp.common.util.StringUtil;
import com.rfsp.common.util.XssUtils;
import com.rfsp.mcp.enums.McpConst;
import com.rfsp.mcp.mapper.AttachMapper;
import com.rfsp.mcp.mapper.AuthHisMapper;
import com.rfsp.mcp.mapper.FinanceHisMapper;
import com.rfsp.mcp.mapper.FinanceMapper;
import com.rfsp.mcp.mapper.FinanceMiInfoMapper;
import com.rfsp.mcp.pojo.dto.AuthDTO;
import com.rfsp.mcp.pojo.dto.BargainDTO;
import com.rfsp.mcp.pojo.dto.FinanceCancelDTO;
import com.rfsp.mcp.pojo.dto.FinanceDTO;
import com.rfsp.mcp.pojo.dto.FinancePDFDTO;
import com.rfsp.mcp.pojo.dto.FinanceVerifyCancelDTO;
import com.rfsp.mcp.pojo.dto.SmsDTO;
import com.rfsp.mcp.pojo.po.AttachPO;
import com.rfsp.mcp.pojo.po.AuthHisPO;
import com.rfsp.mcp.pojo.po.AuthPO;
import com.rfsp.mcp.pojo.po.ContactPO;
import com.rfsp.mcp.pojo.po.FinanceHisPO;
import com.rfsp.mcp.pojo.po.FinanceMiInfoPO;
import com.rfsp.mcp.pojo.po.FinancePO;
import com.rfsp.mcp.pojo.po.OrgYbjPO;
import com.rfsp.mcp.pojo.sdto.FinanceSDTO;
import com.rfsp.mcp.pojo.vo.BankVO;
import com.rfsp.mcp.pojo.vo.FinanceVO;
import com.rfsp.mcp.pojo.vo.HospitalVO;
import com.rfsp.mcp.pojo.vo.PfmVO;
import com.rfsp.mcp.util.McpPdfUtil;

import tk.mybatis.mapper.entity.Example;

@Service
public class FinanceService extends BaseService<FinancePO> {
	
	public Logger logger = LoggerFactory.getLogger(FinanceService.class);
	

    @Autowired
    FinanceMapper financeMapper;
    
    @Autowired
    FinanceHisMapper financeHisMapper;
    
    @Autowired
    FinanceMiInfoMapper financeMiInfoMapper;
    
    @Autowired
    AuthService authService;
    
    @Autowired
    AuthHisMapper authHisMapper;;
    
    
    @Autowired
    AttachMapper attachMapper;
    
    @Autowired
    SystemCodeService systemCodeService;
    
    
	@Autowired
	AreaService areaCodeService;
	
	@Autowired
	PfmService pfmService;
	
	@Autowired
    SmsLoopService smsLoopService;

    @Autowired
    HospitalService hospitalService;

    @Autowired
    BankService bankService;
    
    @Autowired
    OrgService orgService;
    
    @Autowired
    UserService userService;
    
    @Autowired
    OrgYbjService orgYbjService;
    
    @Autowired
    ContactService contactService;
    

	/**融资申请生成pdf保存地址*/
    @Value("${mcp.file-pdf-path-finance}")
    private String filePDFPathFinance;
    
    /**融资申请上传附件保存地址*/
    @Value("${mcp.file-attach-path-finance}")
    private String fileAttachFinancePath;
    

    public PageInfo<FinanceVO> get(FinanceSDTO sdto, PageSDTO pageSdto){
        if(pageSdto!=null){
            PageHelper.startPage(pageSdto.getPageNum(), pageSdto.getPageSize());
        }
        List<FinanceVO> voList=financeMapper.get(sdto);

        PageInfo<FinanceVO> page = new PageInfo(voList);
        return page;
    }

    public FinancePO getByAuthId(Long authId) {
    	return financeMapper.getByAuthId(authId);
    }

    public List<FinanceVO> get(FinanceSDTO sdto){
        List<FinanceVO> voList=financeMapper.get(sdto);
        return voList;
    }
    
    
    public FinancePO getPOBy2Id(Long id, String aid){
    	FinancePO financePO = new FinancePO();
        financePO.setId(id);
        financePO.setAid(aid);
        
        List<FinancePO> financePOList = financeMapper.select(financePO);
        
        if(financePOList != null && !financePOList.isEmpty()) {
        	financePO = financePOList.get(0);
        }else {
        	financePO = null;
        }
        return financePO;
    }
    

    public FinanceVO getById(Long id){
        if(id==null){
            return null;
        }
        FinanceVO vo=new FinanceVO();
        FinancePO e=financeMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(e,vo);

        PfmVO pfm=pfmService.getById(vo.getPfmId());
        vo.setAreaCode(pfm.getAreaCode());

        HospitalVO hospital=hospitalService.getById(vo.getOrgId());
        vo.setOrgName(hospital.getOrgName());

        BankVO bank=bankService.getById(vo.getBankOrgId());
        vo.setBankOrgName(bank.getOrgName());
        return vo;
    }
    
    
    
    public FinanceVO getBy2Id(Long id, String aid){
        if(id==null || aid==null){
            return null;
        }
        
        FinanceVO vo = null;
        
        FinancePO financePO = new FinancePO();
        financePO.setId(id);
        financePO.setAid(aid);
        
        List<FinancePO> financePOList = financeMapper.select(financePO);
        
        if(financePOList != null && !financePOList.isEmpty()) {
        	vo = new FinanceVO();
        	financePO = financePOList.get(0);
        	
        	BeanUtils.copyProperties(financePO, vo);

            PfmVO pfm=pfmService.getById(vo.getPfmId());
            vo.setAreaCode(pfm.getAreaCode());

            HospitalVO hospital=hospitalService.getById(vo.getOrgId());
            vo.setOrgName(hospital.getOrgName());

            BankVO bank=bankService.getById(vo.getBankOrgId());
            vo.setBankOrgName(bank.getOrgName());
        }
        return vo;
    }
    
    public String saveFinanceAfter(FinanceDTO dto) throws Exception {
    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "saveFinanceAfter"));
    	String returnStr = null;
    	
    	
    	
    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "saveFinanceAfter"));
    	return returnStr;
    }
    
    
    public String validateSave(FinanceDTO dto) {
    	String returnStr = null;
		
//		String areaCode = StringUtils.isBlank(dto.getCounty())?(StringUtils.isBlank(dto.getCity())?dto.getProvince():dto.getCity()):dto.getCounty();
//        PfmVO pfmVO = pfmService.getPfmByAreaCode(areaCode);
        
//        if(pfmVO == null) {
//        	return "该地区没有对应的医保平台信息";
//        }
		
		UserPO currentUser = ShiroUtils.getCurrentUser();
		
		Example e = new Example(FinancePO.class);
		e.createCriteria().andEqualTo("pfmId", dto.getPfmId()).andEqualTo("applyUserId", currentUser.getId()).andCondition("(BANK_ORG_ID != "+dto.getBankOrgId()+" and FINANCE_STATUS != '3')");
		int size = financeMapper.selectCountByExample(e);	
		logger.info("当前医保统筹区存在有效融资申请:"+size);
		if(size > 0) {
			return "<span class='noneRecord'>同一医保统筹区不支持向多家资金方发起申请。</span><br/><span>当前医保统筹区存在有效融资申请，如需变更资金方，请先终止原有业务。</span>";
		}
		
		
//		FinancePO financeTemp = new FinancePO();
//		financeTemp.setPfmId(dto.getPfmId());
//        financeTemp.setApplyUserId(currentUser.getId());
//        List<FinancePO> financePOList = financeMapper.select(financeTemp);
//        if(financePOList != null && !financePOList.isEmpty()) {
//        	for(FinancePO financePO:financePOList) {
//        		if((!financePO.getBankOrgId().equals(dto.getBankOrgId())) && !"3".equals(financePO.getFinanceStatus())) {
//        			return "<span class='noneRecord'>同一医保统筹区不支持向多家资金方发起申请。</span><br/><span>当前医保统筹区存在有效融资申请，如需变更资金方，请先终止原有业务。</span>";
//        		}
//        	}
//        }
        return returnStr;
    }
    
    
    public void savePDF(Map<String, Object> maps) throws Exception {
    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "savePDF"));
    	
    	FinancePDFDTO financePDFDTO = (FinancePDFDTO)maps.get("financePDFDTO");
    	Map<String, Object> dataMap = (Map<String, Object>)maps.get("dataMap");
    	String dirPath = (String)maps.get("dirPath");
    	Long miId = (Long)maps.get("miId");

        PfmVO pfm = ShiroUtils.getAttribute("mcp_pfm");
        String pdfPath="";
        if("0".equals(pfm.getItfType()))
            pdfPath = McpPdfUtil.buildFinanceAndMiInfoPDF(financePDFDTO, dataMap, dirPath);
        else {
            pdfPath = McpPdfUtil.buildFinanceAndMiInfoYBDPDF(financePDFDTO, dataMap, dirPath);
        }
        logger.info("pdfPath="+pdfPath);
    	
		FinancePO finance = financeMapper.selectByPrimaryKey(financePDFDTO.getFinanceId());
		
		FinanceMiInfoPO financeMiInfoPO = new FinanceMiInfoPO();
		financeMiInfoPO.setId(miId);
		financeMiInfoPO.setFilePath(pdfPath);
		int i = financeMiInfoMapper.updateByPrimaryKeySelective(financeMiInfoPO);
		logger.info("financeMiInfoPO="+i);
    	
    	//======================================================
        // 张超让存在这，方便文件系统访问时使用
        File financePDF = new File(finance.getFilePath());
        if(financePDF.exists()) {
        	AttachPO attach = new AttachPO();
        	attach.setAid(this.getAID());
            attach.setAttachType("f");
            attach.setDocumentId(finance.getId());
            attach.setDocumentNo(finance.getFinanceNo());
            attach.setOptTime(finance.getOptTime());
            attach.setOptType(finance.getOptType());
            attach.setOptUserId(finance.getOptUserId());
            attach.setUploadTime(finance.getOptTime());
            attach.setFileName(finance.getFilePath());
            attach.setFileSize(financePDF.length()/1048576l);
            attach.setInifileName(financePDF.getName());
            i = attachMapper.insertSelective(attach);
            logger.info("AttachPO="+i);
        }
        
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "savePDF"));
    }
    
    
    //@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
    public Map<String, Object> saveFinance(FinanceDTO dto) throws Exception {
    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "saveFinance"));
    	
    	Map<String, Object> returnMap = new HashMap<String, Object>();
    	
        
		UserPO currentUser = ShiroUtils.getCurrentUser();
		OrgPO currentOrg = ShiroUtils.getCurrentOrg();
		OrgYbjPO orgYbjPO =  ShiroUtils.getAttribute("org_ybj");
		
        Date now = new Date();
        //PDF的创建路径
        String dirPath = filePDFPathFinance.replaceFirst("date", StringUtil.dateToString(now, "yyyy/MM/dd"));
        
        
        FinancePO finance = new FinancePO();
        BeanUtils.copyProperties(dto,finance);
        
        finance.setAid(this.getAID());
        finance.setOrgId(currentOrg.getId());
        finance.setPfmId(dto.getPfmId());
        finance.setFinanceNo(systemCodeService.getBussCode("finance"));
        finance.setFinanceStatus("1");
        finance.setFinanceViewStatus("1");
        finance.setFinanceCurrency("CNY");
        finance.setApplyTime(now);
        finance.setApplyUserId(currentUser.getId());
        finance.setFilePath(dirPath+finance.getFinanceNo()+".pdf");
        finance.setOptTime(now);
        finance.setOptType("1");
        finance.setOptUserId(currentUser.getId());
        finance.setOrgYbjId(orgYbjPO.getId());
        financeMapper.insertSelective(finance);
        
        //保存历史表
        FinanceHisPO financeHisPO = new FinanceHisPO();
        BeanUtils.copyProperties(finance, financeHisPO);
        financeHisPO.setId(null);
        financeHisPO.setFkid(finance.getId());
        financeHisMapper.insertSelective(financeHisPO);
        logger.info("==1_保存融资申请成功==");
        
        
        AuthPO authPO = authService.get(dto.getAuthId());
        authPO.setAuthStatus("1");
        authService.update(authPO);
        logger.info("==2_更新授权状态成功==");
        
        
        //取消附件
//            String attr = XssUtils.replaceUnXssAll(dto.getAttachFileContent());
//            List<AttachFile> fileList=AttachFileUtil.getAttachFileListByContent(XssUtils.replaceUnXssAll(dto.getAttachFileContent()));
//            
//            for(AttachFile attachFile:fileList) {
//            	AttachPO attach = new AttachPO();
//                attach.setAttachType("1");
//                attach.setDocumentId(finance.getId());
//                attach.setDocumentNo(finance.getFinanceNo());
//                String path = fileAttachFinancePath.replaceFirst("date", StringUtil.dateToString(now, "yyyy/MM/dd"));
//                attach.setFileName(path + attachFile.getServerFileName());
//                attach.setFileSize(attachFile.getFileSize());
//                attach.setInifileName(attachFile.getFileName());
//                attach.setOptTime(finance.getOptTime());
//                attach.setOptType(finance.getOptType());
//                attach.setOptUserId(finance.getOptUserId());
//                attach.setUploadTime(finance.getOptTime());
//                
//                attachMapper.insertSelective(attach);
//            }
//            logger.info("==3_保存融资附件成功==");
        
        
        
        //======================生成PDF====================START==============
        String miNo = systemCodeService.getBussCode("mi");
        PfmVO pfm = ShiroUtils.getAttribute("mcp_pfm");
        if(pfm != null) {
            if(!"0".equals(pfm.getItfType()))
                miNo = systemCodeService.getBussCode("mi-pfm");
        }
        
        FinancePDFDTO financePDFDTO = new FinancePDFDTO();
        //地区
        if(StringUtils.isNotBlank(dto.getPfmAreaAddress())) {
        	financePDFDTO.setAreaName(dto.getPfmAreaAddress());
        }

        financePDFDTO.setAuthNo(authPO.getAuthNo());
        financePDFDTO.setAuthEndTime(StringUtil.dateToString(authPO.getAuthEndTime(), "yyyy-MM-dd"));
        financePDFDTO.setAuthStartTime(StringUtil.dateToString(authPO.getAuthStartTime(), "yyyy-MM-dd"));
        
        
        financePDFDTO.setAccountBank(finance.getAccountBank());
        financePDFDTO.setAccountName(finance.getAccountName());
        financePDFDTO.setAccountNo(finance.getAccountNo());
        financePDFDTO.setContactMobile(finance.getContactMobile());
        financePDFDTO.setContactName(finance.getContactName());
        financePDFDTO.setContactTel(finance.getContactTel());
        financePDFDTO.setFinanceAmount(finance.getFinanceAmount().toString());
        financePDFDTO.setFinanceCurrency(finance.getFinanceCurrency());
        financePDFDTO.setFinanceLimit(McpConst.FinanceLimit.getVal(finance.getFinanceLimit()));
        financePDFDTO.setFinanceNo(finance.getFinanceNo());
        financePDFDTO.setFinancePurpose(finance.getFinancePurpose());
        financePDFDTO.setFinanceRemark(finance.getFinanceRemark());
        financePDFDTO.setApplyTime(StringUtil.dateToString(finance.getApplyTime(), "yyyy-MM-dd"));
        financePDFDTO.setFinanceId(finance.getId());
        
        financePDFDTO.setMiId(String.valueOf(currentOrg.getId()));
        financePDFDTO.setMiNo(miNo);
        financePDFDTO.setMiOrgCode(currentOrg.getOrgCode());
        financePDFDTO.setMiOrgName(XssUtils.replaceUnXssAll(currentOrg.getOrgName()));
        financePDFDTO.setMiOrgType(finance.getMiOrgType());
        
        
        String orgAreaCode = StringUtils.isBlank(currentOrg.getCounty())?(StringUtils.isBlank(currentOrg.getCity())?currentOrg.getProvince():currentOrg.getCity()):currentOrg.getCounty();
		financePDFDTO.setMiRegAdr(areaCodeService.getFullAddress(orgAreaCode).replace("-", "")+XssUtils.replaceUnXssAll(currentOrg.getAddress()));


        Map<String,Object> dataMap = orgYbjService.getHospitalPdfMap(orgYbjPO.getId(), orgYbjPO.getAid());
        if(pfm != null) {
            if("0".equals(pfm.getItfType()))
                dataMap = orgYbjService.getHospitalPdfMap(orgYbjPO.getId(), orgYbjPO.getAid());
            else
                dataMap = orgYbjService.getHospitalYBDPdfMap(orgYbjPO.getId(), orgYbjPO.getAid());
        }
        returnMap.put("financePDFDTO", financePDFDTO);
        returnMap.put("dataMap", dataMap);
        returnMap.put("dirPath", dirPath);
        
        logger.info("==3_生成融资PDF所需数据成功==");
        

        FinanceMiInfoPO financeMiInfoPO = new FinanceMiInfoPO();
        financeMiInfoPO.setAid(this.getAID());
        financeMiInfoPO.setMiNo(miNo);
        financeMiInfoPO.setFinanceId(finance.getId());
        financeMiInfoPO.setMiInfo(JsonUtil.toJson(dataMap));
        financeMiInfoPO.setOptTime(finance.getOptTime());
        financeMiInfoPO.setOptType(finance.getOptType());
        financeMiInfoPO.setOptUserId(finance.getOptUserId());
        financeMiInfoPO.setOrgId(currentOrg.getId());
        financeMiInfoMapper.insertSelective(financeMiInfoPO);
        
        returnMap.put("miId", financeMiInfoPO.getId());
        logger.info("==4_保存主体信息成功==");
        
        //========================================END==========
        
        
        
        //======================发短信=====================
        String msg = "尊敬的用户，您好！您在中征应收账款融资服务平台有新的融资请求（中征融资申请编号为"+finance.getFinanceNo()+"），请及时处理。已处理忽略，拒收请回复R。";
        List<UserPO> userPOList = userService.getUserByOrgId(finance.getBankOrgId());
        if(userPOList != null && !userPOList.isEmpty()) {
        	for(UserPO userPO:userPOList) {
        		List<ContactPO> contactPOList = contactService.queryContactByCreator(userPO.getUserCode());
        		if(contactPOList != null && !contactPOList.isEmpty()) {
        			for(ContactPO contactPO:contactPOList) {
        				SmsDTO sms=new SmsDTO();
        	            sms.setMobile(contactPO.getMobile());
        	            sms.setContent(msg);
        	            sms.setUsercode(currentUser.getUserCode());
        	            smsLoopService.create(sms);
        	            logger.info("==短信发送号码："+contactPO.getMobile()+"; 信息："+msg);
        			}
        		}
        	}
        }
        logger.info("==5_发送短信成功==");
        
        logger.info("==融资申请创建完毕==");
            
    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "saveFinance"));
    	return returnMap;
    }
    
    
    /**
     * 融资申请撤销
     * @return FinanceViewStatus  1：未查看 2：已查看
     */
    public String cancelFinance(FinanceCancelDTO financeCancelDTO) {
    	
    	FinancePO finance = this.getPOBy2Id(financeCancelDTO.getId(), financeCancelDTO.getAid());
    	AuthPO auth = authService.get(finance.getAuthId());
    	
    	Date now = new Date();
    	UserPO userPO = ShiroUtils.getCurrentUser();
    	
    	if("1".equals(finance.getFinanceStatus()) && "1".equals(finance.getFinanceViewStatus()) ) {
    		finance.setFinanceStatus("3");
    		finance.setRevokeApplyReason(financeCancelDTO.getRevokeApplyReason());
    		finance.setRevokeApplyTime(now);
    		finance.setRevokeApplyUserName(userPO.getUserName());
    		finance.setRevokeApplyUserId(userPO.getId());
            finance.setOptTime(now);
            finance.setOptType("3");
            finance.setOptUserId(userPO.getId());
    		
    		auth.setAuthStatus("3");
    		auth.setRevokeApplyReason(financeCancelDTO.getRevokeApplyReason());
    		auth.setRevokeApplyTime(now);
    		auth.setRevokeApplyUserName(userPO.getUserName());
    		auth.setRevokeApplyUserId(userPO.getId());
    		auth.setRevokeType("3");
    		auth.setOptTime(now);
            auth.setOptType("3");
            auth.setOptUserId(userPO.getId());
    		
    	}else if("1".equals(finance.getFinanceStatus()) && "2".equals(finance.getFinanceViewStatus()) ) {
    		finance.setRevokeApplyReason(financeCancelDTO.getRevokeApplyReason());
    		finance.setRevokeApplyTime(now);
    		finance.setRevokeApplyUserName(userPO.getUserName());
    		finance.setRevokeApplyUserId(userPO.getId());
    		finance.setRevokeVerifyStatus("1");//撤销审核状态
            finance.setOptTime(now);
            finance.setOptType("2");
            finance.setOptUserId(userPO.getId());
    		
    		auth.setRevokeApplyReason(financeCancelDTO.getRevokeApplyReason());
    		auth.setRevokeApplyTime(now);
    		auth.setRevokeApplyUserName(userPO.getUserName());
    		auth.setRevokeApplyUserId(userPO.getId());
    		auth.setRevokeVerifyStatus("1");//撤销审核状态
    		auth.setRevokeType("2");
    		auth.setOptTime(now);
            auth.setOptType("2");
            auth.setOptUserId(userPO.getId());
    	}else if("2".equals(finance.getFinanceStatus())) {
    		finance.setRevokeApplyReason(financeCancelDTO.getRevokeApplyReason());
    		finance.setRevokeApplyTime(now);
    		finance.setRevokeApplyUserName(userPO.getUserName());
    		finance.setRevokeApplyUserId(userPO.getId());
    		finance.setRevokeVerifyStatus("1");//撤销审核状态
            finance.setOptTime(now);
            finance.setOptType("2");
            finance.setOptUserId(userPO.getId());
    		
    		auth.setRevokeApplyReason(financeCancelDTO.getRevokeApplyReason());
    		auth.setRevokeApplyTime(now);
    		auth.setRevokeApplyUserName(userPO.getUserName());
    		auth.setRevokeApplyUserId(userPO.getId());
    		auth.setRevokeVerifyStatus("1");//撤销审核状态
    		auth.setRevokeType("2");
    		auth.setOptTime(now);
            auth.setOptType("2");
            auth.setOptUserId(userPO.getId());
    	}
    	
    	
    	int fint = financeMapper.updateByPrimaryKeySelective(finance);
    	int aint = authService.update(auth);
    	
    	
    	AuthHisPO authHisPO = new AuthHisPO();
    	BeanUtils.copyProperties(auth, authHisPO);
    	authHisPO.setId(null);
    	authHisPO.setFkid(auth.getId());
    	int ahint = authHisMapper.insertSelective(authHisPO);
    	
    	
    	FinanceHisPO financeHisPO = new FinanceHisPO();
    	BeanUtils.copyProperties(finance, financeHisPO);
    	financeHisPO.setId(null);
    	financeHisPO.setFkid(finance.getId());
    	int fhint = financeHisMapper.insertSelective(financeHisPO);
    	
    	
    	log.info("fint="+fint);
    	log.info("aint="+aint);
    	log.info("fhint="+fhint);
    	log.info("ahint="+ahint);
    	
    	return finance.getFinanceViewStatus();
    }



    private Integer updateById(Long id,FinanceDTO dto){


        dto.setId(id);
        FinancePO e=new FinancePO();
        BeanUtils.copyProperties(dto,e);

        Integer count=this.update(e);

        //保存历史表
        FinanceVO vo=this.getById(id);
        FinanceHisPO hisPO = new FinanceHisPO();
        BeanUtils.copyProperties(vo, hisPO);
        hisPO.setId(null);
        hisPO.setFkid(vo.getId());

        financeHisMapper.insertSelective(hisPO);

        return count;
    }

    public Integer updateVerifyCancel(Long id,FinanceVerifyCancelDTO dto){
        if(dto.getRevokeVerifyRemark()==null || "".equals(dto.getRevokeVerifyRemark())){
            dto.setRevokeVerifyRemark(" ");
        }
        dto.setRevokeVerifyTime(new Date());
        FinanceDTO dto1=new FinanceDTO();
        BeanUtils.copyProperties(dto,dto1);
        //同意后更改成已撤销状态
        if("2".equals(dto1.getRevokeVerifyStatus())){
            dto1.setFinanceStatus("3");

            FinanceVO vo=this.getById(id);
            //更改授权状态
            AuthDTO authDto=new AuthDTO();
            authDto.setAuthStatus("3");
            authService.updateById(vo.getAuthId(),authDto);
        }
        dto1.setOptUserId(dto.getOptUserId());
        dto1.setOptTime(new Date());
        dto1.setOptType("2");
        Integer count=this.updateById(id,dto1);
        return count;
    }
    public Integer updateToViewed(Long id,FinanceDTO dto){
        dto.setFinanceViewStatus("2");
        dto.setOptTime(new Date());
        dto.setOptType("2");
        Integer count=this.updateById(id,dto);
        return count;
    }
    public Integer updateToBargain(Long id,BargainDTO bargain){
        FinanceDTO dto=new FinanceDTO();
        dto.setFinanceStatus("2");

        dto.setOptUserId(bargain.getOptUserId());
        dto.setOptTime(new Date());
        dto.setOptType("2");
        Integer count=this.updateById(id,dto);
        return count;
    }




    public void combo(FinanceVO vo){
        vo.setFinanceStatusStr("");
        if("1".equals(vo.getFinanceStatus())){
            vo.setFinanceStatusStr("已申请");
        }
        if("2".equals(vo.getFinanceStatus())){
            vo.setFinanceStatusStr("已成交");
        }
        if("3".equals(vo.getFinanceStatus())){
            vo.setFinanceStatusStr("已终止");
        }
        
        
        if("1".equals(vo.getRevokeVerifyStatus())){
            vo.setRevokeVerifyStatusName("待审批终止");
        }
        if("2".equals(vo.getRevokeVerifyStatus())) {
            vo.setRevokeVerifyStatusName("同意终止");
        }
        if("3".equals(vo.getRevokeVerifyStatus())) {
            vo.setRevokeVerifyStatusName("拒绝终止");
        }
        
        //地区
        if(StringUtils.isNotBlank(vo.getAreaCode())) {
        	vo.setAreaName(areaCodeService.getFullAddress(vo.getAreaCode()));
        }

    }
    public void combo(List<FinanceVO> voList){
        for(FinanceVO vo:voList ){
            combo(vo);
        }
    }
}
